﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using Microsoft.Win32;

namespace TryCancer
{
    public partial class MainWindow : Window
    {
        String[] listResult;
        listexemple newTest;
        double[][] donnee_app;
        double[][] donnee_gene;
        double weightValue;
        double ageValue;
        double ganglionsValue;
        SystemeNeuronne systeme;
        public MainWindow(){
            InitializeComponent();
            liretext("../../memoryText.txt");
        }

        // On efface les fichiers .mid que l'on avait créé à la fin du programme
        void MainWindow_Closed(object sender, EventArgs e){

        }

        // Clic sur le bouton : on lance la création d'un fichier et on le joue
        private void learningMain(object sender, System.Windows.RoutedEventArgs e)
        {
            newTest = new listexemple("../../CaseFile.txt");
            donnee_app = new double[newTest.nbApprentissage][];
            donnee_gene = new double[newTest.nbGeneralisation][];
            
            for (int i = 0; i < newTest.nbApprentissage; i++)
            {
                donnee_app[i] = newTest.getInfoApprentissage(i);
            }
            for (int j = 0; j < newTest.nbGeneralisation; j++)
            {
                donnee_gene[j] = newTest.getInfoGeneralisation(j);
            }
            LearnandRead();
        }


        private void askResult(object sender, System.Windows.RoutedEventArgs e)
        {
            liretext("../../memoryText.txt");
            int askedWeight = Convert.ToInt32(inputWeight.Text);
            int askedDate = Convert.ToInt32(inputDate.Text);
            int askedGanglions = Convert.ToInt32(inputGanglions.Text);
            double answerCancer = askedWeight * weightValue + askedDate * ageValue + askedGanglions * ganglionsValue;
            if (answerCancer < 0.5)
            {
                labelResult.Content = "Vous allez survivre";
            }
            else if (answerCancer > 0.5)
            {
                labelResult.Content = "Ah bon dommage";
            }
        }
        private void liretext(String filename)
        {
            listResult = File.ReadAllLines(@filename);
            String[] newResult = listResult[0].Split(new Char[] {'.','\t' });
            weightValue = Convert.ToDouble(newResult[0]);
            ageValue = Convert.ToDouble(newResult[1]);
            ganglionsValue = Convert.ToDouble(newResult[2]);
        }

        // Méthode principale
        private void LearnandRead()
        {
            double old_error = Double.PositiveInfinity;
            double total_error = Double.PositiveInfinity;
            double totalGeneralisationError = Double.PositiveInfinity;
            double oldGeneralisationError = Double.PositiveInfinity;
            int betterGeneralisation = 0;
            double rate = 0.1;
            double compteur = 0;
            double taux = 0;
            int d = 0;
            //int nb_neu = neurone.generator.Next(1, 100);
            int nb_neu = 3;
            systeme = new SystemeNeuronne(nb_neu);
            while (d < 10 && betterGeneralisation < 3 && total_error > 0.005)
            {
                
                old_error = total_error;
                total_error = 0;
                oldGeneralisationError = totalGeneralisationError;
                totalGeneralisationError = 0;
                foreach (double[] donne in donnee_app)
                {
                    double sortie = systeme.evaluate(donne);
                    double erreur = donne[3] - sortie;
                    total_error += erreur * erreur;
                    //Console.WriteLine("donne" + donne[3] + " sortie " + sortie + "erreur:" + erreur);
                    systeme.poidsControle(donne, rate);
                }
                foreach (double[] donne in donnee_gene)
                {
                    compteur++;
                    double sortie = systeme.evaluate(donne);
                    double erreur = donne[3] - sortie;
                    totalGeneralisationError += (erreur * erreur);
                    if (sortie < 0.5 && donne[3] == 1)
                    {
                        taux += 1;
                    }
                    else if (sortie > 0.5 && donne[3] == 0)
                    {
                        taux += 1;
                    }

                }
                if (totalGeneralisationError > oldGeneralisationError)
                {
                    betterGeneralisation++;
                }
                if (total_error >= old_error)
                {
                    rate = rate / 2;
                }

                d++;
                Console.WriteLine("total error:" + total_error + "iteration" + d);

            }

            double result = Math.Round(taux / (compteur / 100), 1);
            Console.WriteLine("taux:" + result+" neuronnes:"+nb_neu);

            String resultString = "";
            String pathFile = "../../memoryText.txt";
            double[] resultDouble = systeme.getPoids();
            resultString = resultDouble[0].ToString() + "." + resultDouble[1].ToString() + "." + resultDouble[2].ToString();
            // This text is added only once to the file. 
            if (File.Exists(@pathFile))
            {
                File.WriteAllText(@pathFile, resultString);
                Console.WriteLine("FOUND . TRUTH");
            }
            else
            {
                Console.WriteLine(" NOT FOUND . FALSE");
            }

        }

        void remplissagelabel(Label label, int i)
        {
            string temp = "";
            label.Content = "";
            label.Content = temp;
        }
    }
}
